<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Banner;
use App\Models\Family;
use App\Models\Org;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\User;
use App\Models\UserApply;
use App\Models\UserClock;
use App\Models\UserCollection;
use App\Models\UserProject;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use App\Models\WechatTempMsg;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;

class UserClockController extends Controller
{

    public function create(Request $request)
    {
        $rules = ['code'=>'required|numeric', 'type'=>'required|in:1,2'];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();
        $type = $request->input('type');

        //二维码打卡
        if($type == 1)
        {
            return $this->_clock($request->input('code'));
        }

        //口令打卡
        $date =  date('Y-m-d H:i:s');
        $clockItem = DB::table('project_clock_in')->where('code', $request->input('code'))->where('begin', '<=', $date)->where('end', '>=', $date)->whereRaw("project_id in (select project_id  from user_project where user_id={$userInfo->id})")->whereRaw("id not in (select project_clock_id from user_clock_in where user_id={$userInfo->id})")->first();

        return $this->_clock($clockItem->project_id);
    }

    private function _clock($projectId)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();
        $userProject = UserProject::where('user_id', $userInfo->id)->where('project_id', $projectId)->where('verify_status', 1)->first();


        list($lng, $lat) = explode('-', request()->header('X-location'));
        $check  = UserClock::checkClock($userInfo->id, $projectId, $lng, $lat);

        if(!is_numeric($check))
        {
            $this->setStatus(10001);
            $this->setMsg($check);
            return $this->response();
        }

        $clockItem = DB::table('project_clock_in')->where('id', $check)->first();

        $data['user_id'] = $userInfo->id;
        $data['team_id'] = $userProject->project->team_id;
        $data['org_id'] = $this->getOrdId();
        $data['project_id'] = $projectId;
        $data['project_clock_id'] = $clockItem->id;
        $data['reward_time'] = $clockItem->reward_time;
        $data['clock_in_time'] = date('Y-m-d H:i:s');

        $userClock = new UserClock();
        if($userClock->fill($data)->save())
        {
            $userProject->increment('reward_time', $clockItem->reward_time);
            $userInfo->volunteer->increment('reward_time', $clockItem->reward_time);

            $addScore = $clockItem->reward_time * Org::getScoreConf()['reward_time'];
            $userInfo->volunteer->increment('score', $addScore);
            DB::table('user_score_item')->insert(['user_id'=>$userInfo->id, 'type'=>0, 'score'=>$addScore, 'remark'=>'参加志愿活动']);
            Log::info('SCORE 打卡奖励积分 userId:'.$userInfo->id.'  score:'.$addScore);

        }

        //微信模版消息，志愿者收到签到提醒
        WechatTempMsg::add(5, ['user_clock_id'=>$userClock->id]);

        //微信模版消息，团队收到志愿者签到提醒
        WechatTempMsg::add(51, ['user_clock_id'=>$userClock->id]);

        return $this->index(request());
    }

    public function index(Request $request)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $nodes = UserClock::with('project')->where('user_id', $userInfo->id);
        $nodes = $nodes->orderBy('id', 'desc')->take(1)->skip(0);

        $lists = $nodes->get()->toArray();
        $list = array_map(function($item){

            $tmp = UserClock::format($item);
            $tmp['project'] = Project::format($item['project']);
            return $tmp;
        }, $lists);

        $next = DB::table('project_clock_in')->whereRaw("project_id in (select project_id from user_project where user_id={$userInfo->id} and verify_status=1)")->where('end', '>=', date('Y-m-d H:i:s'))->whereRaw("id not in (select project_clock_id from user_clock_in where user_id={$userInfo->id})")->orderby('begin')->first();


        $data['next'] = (object)[];
        if(!empty($next))
        {
            $data['next']->begin = $next->begin;
            $data['next']->end = $next->end;
            $data['next']->reward_time = $next->reward_time;
            $data['next']->project = Project::format(Project::where('id', $next->project_id)->first());
        }

        $data['list'] = $list;
        $this->setData($data);
        return $this->response();
    }

}
